import base64
from Crypto.Cipher import AES


def add_to_16(value):
    # 中文gbk时占2个字节，utf-8占3个字节
    value = value.encode("utf-8")
    while len(value) % 16 != 0:
        value += "\0".encode()
    return value


def encrypt(key, iv, plaintext):
    cryptor = AES.new(add_to_16(key), AES.MODE_CBC, iv.encode("utf-8"))
    encrypted_text = cryptor.encrypt(add_to_16(plaintext))
    encrypted_text = str(base64.encodebytes(encrypted_text), encoding="utf-8").replace(
        "\n", ""
    )
    return encrypted_text


def decrypt(key, iv, ciphertext):
    # 优先逆向解密base64成bytes
    cryptor = AES.new(add_to_16(key), AES.MODE_CBC, iv.encode("utf-8"))
    base64_decrypted = base64.decodebytes(ciphertext.encode())
    decrypted_text = cryptor.decrypt(base64_decrypted).decode("utf-8")
    decrypted_code = decrypted_text.rstrip("\0")
    return decrypted_code


key = "c07fc7174561aa91"
iv = "c90866af49c1b68a"

text = "D-0001"
enc = encrypt(key, iv, text)

dtext = decrypt(key, iv, enc)
print(text)


dataList = []



for i in range(1, 501):
    data = f"D-{i:04}"
    print("原始数据为：", data)
    enc_str = encrypt(key, iv, data)
    print("加密数据为：", enc_str)
    dataList.append(enc_str)
    dec_str = decrypt(key, iv, enc_str)
    print("解密数据为：", dec_str)


with open("output.txt", "w") as file:
    for d in dataList:
        file.write(d + "\n")



from bike.models import Plate
for i in range(1, 501):
    data = f"D-{i:04}"
    print("原始数据为：", data)
    try:
        plate = Plate.objects.get(number=data)
        print("数据库中已存在该数据")
    except Plate.DoesNotExist:
        plate = Plate(number=data)
        plate.save()
        print("数据库中不存在该数据，已添加")

